package com.java.poc.iofile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class WriteFileExample {
	public static void main(String[] args) {

		File file = new File("c:/newfile.txt");
		String content = "This is the text content";

		try (FileOutputStream fop = new FileOutputStream(file)) {

			// if file doesn't exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// get the content in bytes
			byte[] contentInBytes = content.getBytes();

			fop.write(contentInBytes);
			fop.flush();
			fop.close();

			System.out.println("Done");

		} catch (IOException e) {
			e.printStackTrace();
		}

		try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()))) {
			bw.write("hello ther2e");
		} catch(IOException e) {
			e.printStackTrace();
		}

		try (BufferedWriter bw1 = new BufferedWriter(new FileWriter(file.getName(),true))) {
			bw1.write("hello there1");
		} catch(IOException e) {
			e.printStackTrace();
		}

		try (BufferedReader br1 = new BufferedReader(new FileReader(file)))
		{

			String sCurrentLine;

			while ((sCurrentLine = br1.readLine()) != null) {
				System.out.println(sCurrentLine);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
